package com.example.myapplication.utils


import android.view.Gravity
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.ToastUtils
import com.example.myapplication.R
import com.example.myapplication.model.CallBack
import com.example.myapplication.model.CommentModel
import com.maning.updatelibrary.InstallUtils
import per.goweii.anylayer.AnyLayer
import java.lang.Exception

class DownApkUtils(internal var activity: FragmentActivity) {

    fun installDownApk() {
        CommentModel.getInstant().getcersion(object : CallBack<String> {

            override fun onFailure(fail: String?) {
            }

            override fun onSuccess(t: String, isSuccess: Boolean, msg: String) {
                if (msg.contains("http"))
                    installDownApk(msg)
            }
        })

//
    }

    fun installDownApk(t: String) {
        AnyLayer.dialog(activity)
            .contentView(R.layout.dialog_up_new)
            .backgroundDimDefault()
            .cancelableOnTouchOutside(false)
            .gravity(Gravity.CENTER)
            .bindData { layer ->
                val up_content = layer.getView<TextView>(R.id.up_content);
                val upLoad = layer.getView<TextView>(R.id.upLoad);
                upLoad.setOnClickListener {
                    //shengji
                    up(t)
                    layer.dismiss()
                }

            }
            .show()
    }

    fun up(t: String) {
        AnyLayer.dialog(activity)
            .contentView(R.layout.dialog_up)
            .backgroundDimDefault()
            .cancelableOnTouchOutside(false)
            .gravity(Gravity.CENTER)
            .bindData { layer ->
                val ProgressBar = layer.getView<ProgressBar>(R.id.ProgressBar);
                val speedOfProgress = layer.getView<TextView>(R.id.speedOfProgress);
                val buttonView = layer.getView<View>(R.id.buttonView);
                val content = layer.getView<TextView>(R.id.content);
                val title = layer.getView<TextView>(R.id.title);
                val p1 = layer.getView<View>(R.id.p1);
                layer.getView<View>(R.id.cancel).setOnClickListener { layer.dismiss() }
                title.setText("正在下载")
                p1.visibility = View.VISIBLE
                buttonView.visibility = View.GONE
                content.visibility = View.GONE
                //申请SD卡权限
                if (!PermissionUtils.isGrantSDCardReadPermission(activity)) {
                    PermissionUtils.requestSDCardReadPermission(activity, 100)
                } else {
                    InstallUtils.with(activity)
                        //必须-下载地址
                        .setApkUrl(t)
                        //非必须-下载保存的文件的完整路径+name.apk
//                                                .setApkPath(APK_SAVE_PATH)
                        //非必须-下载回调
                        .setCallBack(object : InstallUtils.DownloadCallBack {
                            override fun onComplete(p0: String) {

                                activity.runOnUiThread {
                                    speedOfProgress.setText("100%")
                                    ProgressBar.setProgress(100)
                                    ToastUtils.showShort("下载成功")
                                    layer.dismiss()
                                    install(p0)
                                }
                            }

                            override fun onFail(p0: Exception?) {
                                activity.runOnUiThread {
                                    ToastUtils.showShort("下载失败" + p0!!.message)
                                    layer.dismiss()
                                }

                            }

                            override fun onLoading(p0: Long, p1: Long) {
                                activity.runOnUiThread {
                                    val progress = (p1 * 100 / p0).toInt()
                                    ProgressBar.setProgress(progress)
                                    speedOfProgress.setText(progress.toString() + "%")
                                }

                            }

                            override fun onStart() {
                                activity.runOnUiThread {
                                    title.setText("正在下载")
                                    speedOfProgress.setText("0%");
                                    ProgressBar.setProgress(0)
                                }

                            }

                            override fun cancle() {
                                activity.runOnUiThread {
                                    ToastUtils.showShort("下载取消")
                                    layer.dismiss()
                                }

                            }
                        })
                        .startDownload()
                }
            }
//                    }
            .show()
    }

    fun install(url: String) {
        //先判断有没有安装权限
        InstallUtils.checkInstallPermission(
            activity,
            object : InstallUtils.InstallPermissionCallBack {
                override fun onGranted() {
                    //去安装APK
                    installApk(url!!)
                }

                override fun onDenied() {
                    AnyLayer.dialog(activity)
                        .contentView(R.layout.dialog_up)
                        .backgroundDimDefault()
                        .cancelableOnTouchOutside(false)
                        .gravity(Gravity.CENTER)
                        .bindData { layer ->
                            val view = layer.getView<TextView>(R.id.content);
                            val cancel = layer.getView<TextView>(R.id.cancel);
                            val enter = layer.getView<TextView>(R.id.enter);
                            view.setText("必须授权才能安装APK，请设置允许安装")
                            cancel.setText("取消")
                            enter.setText("打开")
                            cancel.setOnClickListener { layer.dismiss() }
                            enter.setOnClickListener {
                                InstallUtils.openInstallPermissionSetting(
                                    activity,
                                    object : InstallUtils.InstallPermissionCallBack {
                                        override fun onGranted() {
                                            //去安装APK
                                            installApk(url!!)
                                            layer.dismiss()
                                        }

                                        override fun onDenied() {
                                            //还是不允许咋搞？
                                            ToastUtils.showShort("请开启权限，不然无法安装")
                                        }
                                    })
                                layer.dismiss()
                            }
                        }
                        .show()

                }
            })
    }

    private fun installApk(path: String) {
        InstallUtils.installAPK(activity, path, object : InstallUtils.InstallCallBack {
            override fun onSuccess() {
                //onSuccess：表示系统的安装界面被打开
                //防止用户取消安装，在这里可以关闭当前应用，以免出现安装被取消
                ToastUtils.showShort("正在安装程序")
            }

            override fun onFail(e: Exception) {
                ToastUtils.showShort("安装失败")
            }
        })
    }


}
